package cn.yeziji.netty.server;

import cn.yeziji.netty.config.NettyWebsocketInit;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * netty 服务器
 *
 * @author gzkemays
 * @since 2022/11/07 4:13 PM
 */
@Slf4j
@Component
public class NettyWebsocketServer {
  /** 主线程组 */
  EventLoopGroup bossGroup;
  /** 从线程组 */
  EventLoopGroup workerGroup;
  /** Netty 初始化配置 */
  @Resource NettyWebsocketInit nettyWebsocketInit;

  public void start(int port) {
    // 1. 设置主线程组
    bossGroup = new NioEventLoopGroup(1);
    // 2. 设置从线程组
    workerGroup = new NioEventLoopGroup();
    // 3. 创建线程助手
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap
        .group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .handler(new LoggingHandler())
        .childHandler(nettyWebsocketInit);
    // 绑定 ip 和端口启动服务器
    ChannelFuture sync;
    try {
      sync = serverBootstrap.bind(port).sync();
    } catch (InterruptedException e) {
      close();
      throw new RuntimeException(e);
    }
    log.info("Netty-{} 服务器启动成功", port);
    sync.channel().closeFuture();
  }

  public void close() {
    if (bossGroup != null) bossGroup.shutdownGracefully();
    if (workerGroup != null) workerGroup.shutdownGracefully();
  }
}
